package com.cqs.leetcode;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class String2Integer {

    public int myAtoi(String str) {
        if (str == null || str.length() < 1) return 0;
        StringBuilder sb = new StringBuilder(str.trim());
        if (sb.length() <=0) return  0;
        int sign = 1;
        if (sb.charAt(0) == '-') sign = -1;
        if (sb.charAt(0) == '-' || sb.charAt(0) == '+') sb.deleteCharAt(0);
        Pattern compile = Pattern.compile("^\\d+");
        Matcher matcher = compile.matcher(sb.toString());
        String group = "";
        if (matcher.find()) {
            group = matcher.group();
        }
        //first
        int result = 0;
        for (int i = 0; i < group.length(); i++) {
            System.out.println(result +"\t"+((Integer.MAX_VALUE - group.charAt(i) + '0') / 10));
            if (((Integer.MAX_VALUE - group.charAt(i) + '0') / 10) >= result) {
                result = result * 10 + group.charAt(i) - '0';
            }else {
                return  sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
        }
        return result * sign;
    }

    public static void main(String[] args) {
        String str = " ";
        String2Integer si = new String2Integer();
        int i = si.myAtoi(str);

        System.out.println(i);
//        System.out.println(Integer.MIN_VALUE);

    }
}
